var http = require("http");
const path = require("path");
var url = require("url")
var mongo_module = require("./dbmgr")
var { readStaticFile } = require("./readStaticFile")
var Common = require("./common.js")
const uuid = require('node-uuid')
var express = require('express');

var cookieParser = require('cookie-parser');
// post请求会用到
var bodyParser = require('body-parser')


//创建应用
var app = express();
var server = undefined;

app.use('/static', express.static('static'));
app.use('/editormd', express.static('editormd'));
app.use('/edit/editormd', express.static('editormd'))
//解析json和x-www-form-urlencoded请求
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
//使用cookie管理
app.use(cookieParser())

//处理根目录请求
app.get('/', function (req, res) {
    var file_path = path.join(__dirname, 'static')
    var options = {
        root: file_path,
        headers: {
            "Content-Type": "text/html"
        }
    }
    res.sendFile('index.html', options, function (error) {
        if (error) {
            console.log('Sent failed:', 'index.html' + error);
        } else {
            console.log('Sent sucess:', 'index.html');
        }
    });
})

//返回单个文章浏览界面
app.get('/article/:id', function (req, res) {
    console.log("req.params.id is ", req.params.id)

    var file_path = path.join(__dirname, 'static')
    var options = {
        root: file_path,
        headers: {
            "Content-Type": "text/html"
        }
    }
    res.sendFile('article.html', options, function (error) {
        if (error) {
            console.log('Sent failed:', 'article.html' + error);
        } else {
            console.log('Sent sucess:', 'article.html');
        }
    });
})

//处理请求发布页面
app.get('/publish', (req, res) => {
    var file_path = path.join(__dirname, 'static')
    var options = {
        root: file_path,
        headers: {
            "Content-Type": "text/html"
        }
    }
    res.sendFile('publish.html', options, function (error) {
        if (error) {
            console.log('Sent failed:', 'publish.html' + error);
        } else {
            console.log('Sent sucess:', 'publish.html');
        }
    });
})

//处理发布文章请求
app.post('/publish-article', async function (req, res) {
    let body = req.body
    console.log("req body is ",)
    // 输出 JSON 格式
    let findres = await mongo_module.FindArticleByTitle(body.title)
    if (findres != 0) {
        console.log("title is existed")
        var resbody = {
            "errorcode": findres,
        }

        res.writeHead(200, { 'Content-Type': 'application/json ; charset=utf8' });
        var resjson = JSON.stringify(resbody)
        res.end(resjson);
        return;
    }

    let time_data = Common.GetTime();
    console.log("time_data is ", time_data)
    body['created'] = time_data
    body['updated'] = time_data
    body['artid'] = uuid.v1()

    insertres = await mongo_module.InsertArticle(body)
    var resbody = {
        "errorcode": insertres,
    }

    res.writeHead(200, { 'Content-Type': 'application/json ; charset=utf8' });

    res.end(JSON.stringify(resbody));
})

//按页码返回文章列表
app.post('/article-list', async function (req, res) {
    let body = req.body
    //console.log("req body is ", body)
    var resbody = {
        "errorcode": 0,
    }

    var count_res = await mongo_module.TotalArticleCounts(resbody)
    if (count_res != 0) {
        resbody.errorcode = count_res
        res.writeHead(200, { 'Content-Type': 'application/json ; charset=utf8' });
        var resjson = JSON.stringify(resbody)
        res.write(resjson)
        res.end();
        return
    }

    var find_res = await mongo_module.FindArticleListByPage(body.curpage, resbody)
    if (find_res != 0) {
        resbody.errorcode = find_res
        res.writeHead(200, { 'Content-Type': 'application/json ; charset=utf8' });
        var resjson = JSON.stringify(resbody)
        res.write(resjson)
        res.end();
        return;
    }

    res.writeHead(200, { 'Content-Type': 'application/json ; charset=utf8' });
    var resjson = JSON.stringify(resbody)
    res.write(resjson)
    res.end();

})

//请求文章详情
app.post('/article-detail', async (req, res) => {
    let body = req.body
    console.log("body is ", body)
    var resbody = {
        "errorcode": 0,
    }

    let find_res = await mongo_module.FindArticleById(body['article_id'], resbody)
    if (find_res != 0) {
        resbody.errorcode = find_res
        res.writeHead(200, { 'Content-Type': 'application/json ; charset=utf8' })
        var resjson = JSON.stringify(resbody)
        res.write(resjson)
        res.end();
        return
    }

    res.writeHead(200, { 'Content-Type': 'application/json ; charset=utf8' });
    var resjson = JSON.stringify(resbody)
    res.write(resjson)
    res.end();
})

//返回重新编辑页面
app.get('/edit/:id', function (req, res) {
    console.log("req.params.id is ", req.params.id)

    var file_path = path.join(__dirname, 'static')
    var options = {
        root: file_path,
        headers: {
            "Content-Type": "text/html"
        }
    }
    res.sendFile('edit.html', options, function (error) {
        if (error) {
            console.log('Sent failed:', 'edit.html' + error);
        } else {
            console.log('Sent sucess:', 'edit.html');
        }
    });
})

//更新文章列表
app.post('/update-article', async (req, res) => {
    var body = req.body
   // console.log("body is ", body)

    var resbody = {
        "errorcode": 0,
    }

    let find_res = await mongo_module.FindArticleById(body['artid'], resbody)
    if (find_res != 0) {
        resbody.errorcode = find_res
        res.writeHead(200, { 'Content-Type': 'application/json ; charset=utf8' })
        var resjson = JSON.stringify(resbody)
        res.write(resjson)
        res.end();
        return
    }

    let time_data = Common.GetTime();
    console.log("time_data is ", time_data)
    body['updated'] = time_data

    let update_res = await mongo_module.UpdateArticleById(body, resbody)
    resbody.errorcode = update_res
    res.writeHead(200, { 'Content-Type': 'application/json ; charset=utf8' })
    var resjson = JSON.stringify(resbody)
    res.write(resjson)
    res.end();
})

//返回删除文章后的页面
app.post('/delete-article', async function (req, res) {
    let body = req.body
    console.log("req body is ", body)
    var resbody = {
        "errorcode": 0,
    }
    var del_code = await mongo_module.DelArticleById(body["artid"], resbody)
  
    resbody.errorcode = del_code
    res.writeHead(200, { 'Content-Type': 'application/json ; charset=utf8' })
     var resjson = JSON.stringify(resbody)
        res.write(resjson)
        res.end();
        return
   
})

async function AsyncInitServer() {
    return await InitServerPromise();
}

function InitServerPromise() {

    return new Promise((resolve, reject) => {
        try {
            server = app.listen(3000, function () {
                var host = server.address().address
                var port = server.address().port

                console.log("server http://%s:%s", host, port)
                resolve(server)
            })
        } catch (err) {
            reject(undefined)
        }
    })
}



module.exports.App = app;
module.exports.AsyncInitServer = AsyncInitServer
